package com.auxgroup.hr.front.site.co.process;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import com.auxgroup.hr.front.dao.domain.PsCModAttT;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.auxgroup.hr.front.commons.config.BusinessConfig;
import com.auxgroup.hr.front.commons.utils.File2Byte;
import com.auxgroup.hr.front.dao.domain.PsCWfFileAtt;
import com.auxgroup.hr.front.service.process.WfFileService;
import com.auxgroup.hr.front.site.co.BaseCO;

/**
 * 流程附件下载
 * @author lv-PC
 *
 */
@Controller
@RequestMapping("/download")
public class WfFileDownloadCO extends BaseCO {

	private static final Logger logger = LoggerFactory.getLogger(WfFileDownloadCO.class);
	
	@Autowired
	private WfFileService wfFileService;
	
	@Autowired
	private BusinessConfig businessConfig;
	
	/**
	 * 获取岗位薪酬变动审批信息
	 * @return
	 */
	@GetMapping(value = "/wfFile")
	public void downWfFile(String cTransactionNbr,BigDecimal seqnbr,HttpServletResponse response) {
		logger.info("downWfFile cTransactionNbr:{},seqnbr:{}", cTransactionNbr,seqnbr);
		PsCModAttT filtAtt = wfFileService.getFileAttInfos(cTransactionNbr,seqnbr);
		if(filtAtt==null){
			return;
		}
		File wfFile = new File(businessConfig.getFtpFileResourceLocation()+"/"+filtAtt.getAttachsysfilename());
		response.reset();
		response.setCharacterEncoding("utf-8");
		response.addHeader("Content-Disposition", "attachment;filename=" + filtAtt.getAttachsysfilename());
		response.addHeader("Content-Length",String.valueOf(wfFile.length()));
	    response.setContentType("application/octet-stream;charset=UTF-8");
	    logger.info("contentType:{}",response.getContentType());
	    List<String> heardnames = ( List<String>)response.getHeaderNames();
	    for (String name : heardnames) {
			logger.info("heard:{}={}",name,response.getHeader(name));
		}
	    try {
		    OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());  
		    outputStream.write(File2Byte.file2Bytes(wfFile));
		    outputStream.flush();  
		    outputStream.close();  
	    } catch (IOException e) {
	          logger.error("read ftp file failed：",e);
	    }
	}
	
}
